package main

import (
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"

	_ "github.com/mattn/go-sqlite3"
)

type QuestionAnswer struct {
	Question string
	Answer   []string
}

func getAnswers(key string) ([]QuestionAnswer, error) {
	if key == "" {
		return nil, errors.New("Empty Key Word")
	}
	var ret = []QuestionAnswer{}
	db, err := sql.Open("sqlite3", "data.db")
	if err != nil {
		return nil, err
	}
	defer db.Close()
	rows, err := db.Query("SELECT question,answers FROM answers where question like ?;", "%"+key+"%")
	if err != nil {
		fmt.Println(err.Error())
		return nil, err
	}
	for {
		if rows.Next() == false {
			break
		}
		var question, answers string
		err = rows.Scan(&question, &answers)
		if err != nil {
			fmt.Println(err.Error())
			break
		}
		var answers_v []string
		err = json.Unmarshal([]byte(answers), &answers_v)
		if err != nil {
			fmt.Println(err.Error())
			break
		}

		v := QuestionAnswer{Question: question, Answer: answers_v}
		ret = append(ret, v)
	}

	return ret, rows.Close()
}
